package com.irdstudio.apicenter.console.controller.make;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSON;

public class GetAppTree {
	private static List fileList = null;
	private static int layer = 0;

	public static String getAppTree(String absolutePath) throws Exception {
		fileList = new ArrayList();
		layer = 1;
		// File file = new File("D:/CmisDev/WorkSpaceAccount/zqjr");
		File file = new File(absolutePath);
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("id", 1);
		map.put("pId", 0);
		map.put("name", file.getName());
		map.put("open", false);
		fileList.add(map);
		iteratorFile(file, 1);
		String jsonStr = JSON.toJSONString(fileList);
		return jsonStr;
	}

	// 遍历目录并输出
	private static void iteratorFile(File file, int pId) {
		File[] files = file.listFiles();
		files = sortFile(files);
		for (int i = 0; i < files.length; i++) {
			File f = files[i];
			if (!f.getName().startsWith(".")) {
				Map<String, Object> map = new HashMap<String, Object>();
				// StringBuffer sb = new StringBuffer();
				// sb.append(getSpaces(layer)).append("  ├"+f.getName());
				// fileList.add(sb.toString());
				layer++;
				map.put("id", layer);
				map.put("pId", pId);
				map.put("name", f.getName());
				if (f.isDirectory() && f.list().length > 0) {
					// 每个目录的下一层文件(或者目录)都要加上两个空格
					int nextPid = layer;
					map.put("open", false);
					fileList.add(map);
					iteratorFile(f, nextPid);
					// 遍历完了之后再恢复
				} else {
					// 出口点
					map.put("file", f.getAbsolutePath());
					fileList.add(map);
				}

			}
		}
	}

	// 排序文件:规则————目录在文件的前面
	private static File[] sortFile(File[] files) {
		List<File> list = new ArrayList<File>();
		for (File f : files) {
			if (f.isDirectory()) {
				list.add(f);
			}
		}
		for (File f : files) {
			if (f.isFile()) {
				list.add(f);
			}
		}
		return list.toArray(new File[files.length]);
	}
}
